// TODO: use dva/fetch after dva@1.2
import fetch from 'dva/fetch';
import config from './config';
import crypt from './crypt';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}
const apiAddress = config.apiServer;
export function request(url, options) {
  return fetch(`${apiAddress}${url}`, options)
    .then(checkStatus)
    .then(parseJSON)
    .catch((err) => ({ err }));
}

/**
 * GET headers
 * @param {*user} user 
 */
function getHeaders(user) {
  // 获取时间戳
  function getTimestamp() {
    return new Date().getTime();
  }
  //获取随机数
  function getRandom(num) {
    let res = "";
    const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    for (var i = 0; i < num; i++) {
      const id = Math.ceil(Math.random() * 35);
      res += chars[id];
    }
    return res;
  }
  // GET Signature
  function getSignature(user) {
    if (user == undefined) {
      user = {
        guid: '80f3b7c5-da2c-406c-a0d8-7e523b371642',
        signToken: '4847a513-d551-465f-81db-567a69513eea'
      }
    }
    const { guid, signToken } = user;
    const timestamp = getTimestamp();
    const nonce = getRandom(9);
    const staffid = guid;
    const st = signToken;
    const private_key = 'qyMZXTMIePOIvObrHPzUGSW6mNscKilAPXPb'; //私钥
    const signStr = timestamp + nonce + staffid + st+private_key;
    const signature = crypt.md5(signStr);
    return {
      timestamp,
      nonce,
      staffid,
      signature
    };
  }
  const token = getSignature(user);
  return {
    'Content-Type': 'application/json',
    'staffid': token.staffid,
    'timestamp': token.timestamp,
    'nonce': token.nonce,
    'signature': token.signature
  };
}

export function postOptions(req) {

  const options = {
    method: "POST",
    body: JSON.stringify(req.body),
    headers: getHeaders(req.session.user)
  };
  return options;
}
export function getOptions(req) {
  const options = {
    method: "GET",
    body: JSON.stringify(req.body),
    headers: getHeaders(req.session.user)
  };
  return options;
}